package org.jeecg.modules.demo.cashier;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.mall.entity.YxStoreCoupon;
import org.jeecg.modules.demo.mall.entity.YxStoreCouponUser;
import org.jeecg.modules.demo.mall.yxstorecoupon.service.IYxStoreCouponService;
import org.jeecg.modules.demo.mall.yxstorecouponuser.service.IYxStoreCouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 优惠券记录表
 * @Author: jeecg-boot
 * @Date: 2023-11-09
 * @Version: V1.0
 */
@Api(tags = "优惠券")
@RestController
@RequestMapping("/mall/cashierCouponUser/cashiercouponuser")
@Slf4j
public class CashierCouponUserController extends JeecgController<YxStoreCouponUser, IYxStoreCouponUserService> {
    @Autowired
    private IYxStoreCouponUserService yxStoreCouponUserService;
    @Autowired
    private IYxStoreCouponService yxStoreCouponService;


    /**
     * 优惠券list
     *
     * @param req
     * @return
     */
    @SneakyThrows
    @ApiOperation(value = "优惠券list", notes = "优惠券list")
    @GetMapping(value = "/queryList")
    public Result<List<YxStoreCouponUser>> queryList(YxStoreCouponUser req,
                                                     @RequestParam(name = "current", defaultValue = "1") Integer current,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //判断符合门店的优惠券
        LambdaQueryWrapper<YxStoreCoupon> couponQueryWrapper = new LambdaQueryWrapper<>();
        //状态开启的优惠券
        couponQueryWrapper.eq(YxStoreCoupon::getStatus, 1);
        //无门店要求、本门店可用
        couponQueryWrapper.and(queryWrapper -> queryWrapper.like(YxStoreCoupon::getMerIds, req.getMerId()).or().eq(YxStoreCoupon::getIsMer, 0));
        //根据符合条件的优惠券查询用户对应数据   为null 则是全部门店的优惠券  不为null则是当前商品可用
        if (StringUtils.isNotBlank(req.getProductId())) {
            couponQueryWrapper.and(queryWrapper1 -> queryWrapper1.like(YxStoreCoupon::getProductId, req.getProductId()).or().eq(YxStoreCoupon::getIsProduct, 0));
            couponQueryWrapper.eq(YxStoreCoupon::getMerType, req.getMerType());
        }
        if (req.getIsProduct() != null) {
            couponQueryWrapper.eq(YxStoreCoupon::getIsProduct, req.getIsProduct());
        }
        //判断没有过期的优惠券
        couponQueryWrapper.and(queryWrapper3 -> queryWrapper3.apply("end_time >= '" + sdf.format(new Date()) + "'").or().eq(YxStoreCoupon::getIsFixedDate, 0));
        //如果只能通用使用
        if (req.getUserCouponType() != null && req.getUserCouponType().equals(0)) {
            couponQueryWrapper.eq(YxStoreCoupon::getType, req.getUserCouponType());
        }
//        if (req.getCouponType() != null) {
//            couponQueryWrapper.eq(YxStoreCoupon::getCouponType, req.getCouponType());
//        }
        //根据金额进行判断
//        if (req.getUseMinPrice() != null) {
//            couponQueryWrapper.le(YxStoreCoupon::getUseMinPrice, req.getUseMinPrice());
//        }
        List<YxStoreCoupon> yxStoreCouponList = yxStoreCouponService.list(couponQueryWrapper);
//获取对饮优惠券  如果没有则进行查询用户所有优惠券
        if (CollectionUtils.isEmpty(yxStoreCouponList)) {
            List<YxStoreCouponUser> not = yxStoreCouponService.queryNot(req);
            if (CollectionUtils.isEmpty(not)) {
                return Result.ok(new ArrayList<YxStoreCouponUser>());
            }
            return Result.ok(not);
        }
        List<Integer> couponInteger = yxStoreCouponList.stream().map(YxStoreCoupon::getId).collect(Collectors.toList());
        //查询用户优惠券。
        //修改过期日期的数据
        yxStoreCouponService.updateExpireDate(req);
        //查询符合条件的数据
        LambdaQueryWrapper<YxStoreCouponUser> yxStoreCouponUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yxStoreCouponUserLambdaQueryWrapper.in(YxStoreCouponUser::getCid, couponInteger);
        yxStoreCouponUserLambdaQueryWrapper.eq(YxStoreCouponUser::getStatus, 0);
        yxStoreCouponUserLambdaQueryWrapper.eq(YxStoreCouponUser::getUid, req.getUid());
//        yxStoreCouponUserLambdaQueryWrapper.orderByDesc(YxStoreCouponUser::getUseMinPrice);
//        IPage<YxStoreCouponUser> page = new Page<>(current, pageSize);
//        IPage<YxStoreCouponUser> users = yxStoreCouponUserService.page(page, yxStoreCouponUserLambdaQueryWrapper);
        List<YxStoreCouponUser> users = yxStoreCouponUserService.list(yxStoreCouponUserLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(users)) {
            List<YxStoreCouponUser> not = yxStoreCouponService.queryNot(req);
            if (CollectionUtils.isEmpty(not)) {
                return Result.ok(new ArrayList<YxStoreCouponUser>());
            }
            return Result.ok(not);
        }
        //如果商品不为空  那么需要查询当前门店其他商品

        if (req.getProductId() != null) {
            //查询不符合条件的数据
            List<YxStoreCouponUser> isNotCoupon = yxStoreCouponService.queryIsNotCoupon(req);
            //根据条件修改优惠券的使用状态
            List<YxStoreCouponUser> isCouponUser = yxStoreCouponService.updateCoupon(req, users);
            //追加 不属于当前商品  的优惠券

            if (!CollectionUtils.isEmpty(isNotCoupon)) {
                isCouponUser.addAll(isNotCoupon);

            }

            return Result.ok(isCouponUser);
        }

        users.forEach(item -> {
            item.setIsUsage(0);
        });
//        users.setRecords(users);
        return Result.OK(users);
    }


    @GetMapping(value = "/editCouponUser")
    public void edit(@RequestParam Integer couponId, @RequestParam String orderNo) {
        //使用
        if (couponId != 0 && StringUtils.isNotBlank(orderNo)) {
            LambdaQueryWrapper<YxStoreCouponUser> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(YxStoreCouponUser::getId, couponId);
            queryWrapper.eq(YxStoreCouponUser::getStatus, 0);
            YxStoreCouponUser byId = yxStoreCouponUserService.getOne(queryWrapper);
            if (byId != null) {
                byId.setStatus(1);
                byId.setOrderNo(orderNo);
                byId.setUseTime(new Date());
                yxStoreCouponUserService.updateById(byId);
            }
        }
        //退回
        if (StringUtils.isNotBlank(orderNo) && couponId == 0) {
            LambdaQueryWrapper<YxStoreCouponUser> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(YxStoreCouponUser::getOrderNo, orderNo);
            YxStoreCouponUser byId = yxStoreCouponUserService.getOne(queryWrapper);
            if (byId != null) {
                if (byId.getEndTime() != null && byId.getEndTime().compareTo(new Date()) < 0) {
                    byId.setStatus(2);
                }
                byId.setStatus(0);
                yxStoreCouponUserService.updateById(byId);
            }
        }
    }


    /**
     * 分页列表查询
     *
     * @param yxStoreCouponUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/listCouponUser")
    public Result<IPage<YxStoreCouponUser>> queryPageList(YxStoreCouponUser yxStoreCouponUser,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        yxStoreCouponUserService.updateExpireDate(yxStoreCouponUser.getUid());


        //判断符合门店的优惠券
        LambdaQueryWrapper<YxStoreCoupon> couponQueryWrapper = new LambdaQueryWrapper<>();
        //状态开启的优惠券
        couponQueryWrapper.eq(YxStoreCoupon::getStatus, 1);
        //无门店要求、本门店可用
        couponQueryWrapper.and(queryWrapper -> queryWrapper.like(YxStoreCoupon::getMerIds, yxStoreCouponUser.getMerId()).or().eq(YxStoreCoupon::getIsMer, 0));
        List<YxStoreCoupon> yxStoreCouponList = yxStoreCouponService.list(couponQueryWrapper);
        if (yxStoreCouponList == null) {
            return Result.ok(new Page<YxStoreCouponUser>());
        }
        List<Integer> couponInteger = yxStoreCouponList.stream().map(YxStoreCoupon::getId).collect(Collectors.toList());

        QueryWrapper<YxStoreCouponUser> queryWrapper = new QueryWrapper<>();
        if (yxStoreCouponUser.getStatus() != null) {
            queryWrapper.eq("status", yxStoreCouponUser.getStatus());
        }
        queryWrapper.eq("uid", yxStoreCouponUser.getUid());
        queryWrapper.in("cid", couponInteger);
        Page<YxStoreCouponUser> page = new Page<YxStoreCouponUser>(pageNo, pageSize);
        IPage<YxStoreCouponUser> pageList = yxStoreCouponUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

}
